//
//  ChapterHead.swift
//  Spookiness
//
//  Created by 腾億 on 2017/12/18.
//  Copyright © 2017年 tml. All rights reserved.
//

import UIKit
//当一个闭包作为参数传到一个函数中，需要这个闭包在函数返回之后才被执行，称为逃逸闭包
//声明闭包
typealias ChapterCHeadSortClosure = (_ button: UIButton) -> Void

class ChapterHead: UICollectionReusableView {
    //持有闭包
    fileprivate var sortClosure: ChapterCHeadSortClosure?
    
    fileprivate lazy var chapterLB: UILabel = {
       let label = UILabel()
        label.textColor = UIColor.gray
        label.font = UIFont.systemFont(ofSize: 13)
        return label
    }()
    
    fileprivate lazy var sortBtn: UIButton = {
       let button = UIButton(type: .custom)
        button.setTitle("倒序", for: .normal)
        button.setTitleColor(UIColor.gray, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        button.addTarget(self, action: #selector(sortAction(_ :)), for: .touchUpInside)
        return button
    }()
    
    @objc fileprivate func sortAction(_ button: UIButton) {
        //这是直接调用
//        self.sortClosure!(button)
        guard let sortClosure = sortClosure else {
            return
        }
        sortClosure(button)
    }
    
    func sortClouse(_ closure: @escaping ChapterCHeadSortClosure) {
        sortClosure = closure
    }
    
    fileprivate func setUpSnap() {
        self.sortBtn.snp.makeConstraints { (make) in
            make.right.top.bottom.equalToSuperview()
            make.width.equalTo(44)
        }
        
        self.chapterLB.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.top.bottom.equalToSuperview()
            make.right.equalTo(sortBtn.snp.left).offset(-10)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(self.chapterLB)
        addSubview(self.sortBtn)
        setUpSnap()
    }
    
    var model: DetailStaticModel? {
        didSet{
            guard let model = model else {
                return
            }
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM-dd"
            chapterLB.text = "目录 \(format.string(from: Date(timeIntervalSince1970: TimeInterval(model.comic?.last_update_time ?? 0)))) 更新 \(model.chapter_list.last?.name ?? "")"
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
